package com.molichuxing.gateway.utils;

import com.alibaba.fastjson.JSON;
import com.molichuxing.framework.contants.RedisKeyConst;
import com.molichuxing.framework.utils.Md5Util;
import com.molichuxing.framework.utils.RedisUtil;
import com.molichuxing.framework.utils.StringUtil;
import com.molichuxing.services.infrastructure.dto.response.response.GroupDto;
import com.molichuxing.services.infrastructure.dto.response.response.GroupResourceDto;
import com.molichuxing.services.infrastructure.dto.response.response.ResourceDto;
import com.molichuxing.services.infrastructure.service.GroupResourceService;
import com.molichuxing.services.infrastructure.service.GroupService;
import com.molichuxing.services.infrastructure.service.ResourceService;
import com.molichuxing.services.property.GroupSystemTypeEnum;
import com.molichuxing.services.property.StatusEnum;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 权限认证工具类
 * 
 * @author 刘瑞丰
 * @date 2019年10月28日
 *
 */
@Component
public class RedisPermissionUtil implements ApplicationListener<ContextRefreshedEvent> {
	private static final Logger logger = LoggerFactory.getLogger(RedisPermissionUtil.class);

	@Resource
	private GroupService  groupService;

	@Resource
	private GroupResourceService groupResourceService;

	@Resource
	private ResourceService resourceService;

	@Resource
	private RedisUtil redisUtil;

	// 环境
	@Value("${profiles.active}")
	private String active;

	/**
     * 启动后加载所有角色对应权限到redis
	 * @param event
	 */
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		setResourceToRedisByTotalGroup();
	}

	public void setResourceToRedisByTotalGroup() {
		Map<String, Object> getGroupParam = new HashMap<>();
		getGroupParam.put("groupSystemType", GroupSystemTypeEnum.DEALER.getValue());
		getGroupParam.put("status", StatusEnum.OPEN.getValue());
		List<GroupDto> groupList = groupService.getGroupListByParm(getGroupParam);
		if (CollectionUtils.isNotEmpty(groupList)) {
			groupList.forEach(groupDto -> {
				resourceToRedis(groupDto.getId());
			});
		}
	}

	/**
	 * 将角色绑定的权限放入redis
	 * @param groupId
	 */
	public synchronized void resourceToRedis(int groupId) {
		String dbType = null;
		if (groupId > 0) {
			String key =  RedisKeyConst.DEALER_GROUP_PERMISSION + Md5Util.md5Hex(active) +"."+  Md5Util.md5Hex(String.valueOf(groupId));
			redisUtil.del(key);

			final List<Integer> resourceIds = new ArrayList<>();

			//查询角色与权限的关联表
			Map<String, Object> getGroupResourceParam = new HashMap<>();
			getGroupResourceParam.put("groupId", groupId);
			List<GroupResourceDto> groupResourceList = groupResourceService.getGroupResourceListByParm(getGroupResourceParam);
			if (CollectionUtils.isNotEmpty(groupResourceList)) {
				groupResourceList.forEach(groupResource -> {
					resourceIds.add(groupResource.getResourceId()); //将角色拥有的权限id放入集合
				});
			}

			//查询角色所拥有的权限
			if (CollectionUtils.isNotEmpty(resourceIds)) {
				Map<String, Object> getResourceMap = new HashMap<>();
				getResourceMap.put("ids", resourceIds);
				List<ResourceDto> rsourceList = resourceService.getResourceListByParam(getResourceMap);
				if (CollectionUtils.isNotEmpty(rsourceList)) {
					final Map<String, String> collect = new HashMap<String, String>();
					rsourceList.forEach(resourceDto -> {
						if (!StringUtil.isEmpty(resourceDto.getUri())) {
							String[] uriArr = resourceDto.getUri().split(",");
							if (uriArr.length > 1) {
								for (String uri : uriArr) {
									if (collect.get(uri) == null) {
										collect.put(uri, Boolean.TRUE.toString());
									}
								}
							} else {
								if (collect.get(resourceDto.getUri()) == null) {
									collect.put(resourceDto.getUri(), Boolean.TRUE.toString());
								}
							}
						}

					});
					redisUtil.hmset(key, collect);
				}
			}
		}
	}

	/**
	 * 删除指定角色得权限数据
	 * @param groupId
	 */
	public synchronized void deleteResourceByGroupId(Integer groupId) {
		if (groupId != null && groupId > 0) {

			String key = RedisKeyConst.DEALER_GROUP_PERMISSION + Md5Util.md5Hex(active) +"."+  Md5Util.md5Hex(groupId+"");;
			redisUtil.del(key);
		}
	}
}
